<template>
    <div>
        <input type="file" id="uploads" style="display:none;" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 2)">
        <mt-actionsheet
            :actions="actions"
            v-model="showImg">
        </mt-actionsheet>
    </div>
</template>
<script>
    import {
        MessageBox
    } from 'mint-ui';
    export default {
        data() {
            return {
                actions: [{
                    name: '拍照',
                    method: this.paizhao
                }, {
                    name: '从相册中选择',
                    method: this.selectImg
                }],
                useInfo: '',
                showImg: this.value,
            }
        },
        props: ['value'],
        methods: {
            paizhao() {
                this.$api.getImage((p, url) => {
                    let exampleImg = url
                    sessionStorage.setItem('exampleImg', JSON.stringify(exampleImg));
                    this.$router.push({
                        'path': '/cropper'
                    })
                })
                console.log('拍照');
            },
            selectImg() {
                document.getElementById("uploads").click();
            },
            uploadImg(e, num) { //从相册选取文件
                var file = e.target.files[0]
                if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                    MessageBox('提示', '图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
                    return false
                }
                var reader = new FileReader()
                reader.onload = (e) => {
                        let data
                        if (typeof e.target.result === 'object') {
                            // 把Array Buffer转化为blob 如果是base64不需要
                            data = window.URL.createObjectURL(new Blob([e.target.result]))
                        } else {
                            data = e.target.result
                        }
                        if (num === 1) {
                            this.option.img = data
                        } else if (num === 2) {
                            let exampleImg = data
                            sessionStorage.setItem('exampleImg', JSON.stringify(exampleImg));
                            this.$router.push({
                                'path': '/cropper'
                            })
                        }
                    }
                    // 转化为base64
                    // reader.readAsDataURL(file)
                    // 转化为blob
                reader.readAsArrayBuffer(file)
            },

        },
        watch: {
            value(newValue) {
                this.showImg = newValue;
            },
            showImg(newValue) {
                this.$emit('input', newValue)
            }

        }
    }
</script>